#!/usr/bin/env bash

set -ve

export LFS='/mnt/lfs'

_USER=`whoami`
if [ "$_USER" != "lfs" ];
then
    echo 'WARNING: User lfs ONLY!!!' && exit;
fi

################################ GCC ################################

cd $LFS/sources/gcc-8.2.0/

cat gcc/limitx.h gcc/glimits.h gcc/limity.h > \
  `dirname $($LFS_TGT-gcc -print-libgcc-file-name)`/include-fixed/limits.h

for file in gcc/config/{linux,i386/linux{,64}}.h
do
  cp -uv $file{,.orig}
  sed -e 's@/lib\(64\)\?\(32\)\?/ld@/tools&@g' \
      -e 's@/usr@/tools@g' $file.orig > $file
  echo '
#undef STANDARD_STARTFILE_PREFIX_1
#undef STANDARD_STARTFILE_PREFIX_2
#define STANDARD_STARTFILE_PREFIX_1 "/tools/lib/"
#define STANDARD_STARTFILE_PREFIX_2 ""' >> $file
  touch $file.orig
done

case $(uname -m) in
  x86_64)
    sed -e '/m64=/s/lib64/lib/' \
        -i.orig gcc/config/i386/t-linux64
  ;;
esac

mkdir -pv build2/
cd build2/

CC=$LFS_TGT-gcc                                    \
CXX=$LFS_TGT-g++                                   \
AR=$LFS_TGT-ar                                     \
RANLIB=$LFS_TGT-ranlib                             \
../configure                                       \
    --prefix=/tools                                \
    --with-local-prefix=/tools                     \
    --with-native-system-header-dir=/tools/include \
    --enable-languages=c,c++                       \
    --disable-libstdcxx-pch                        \
    --disable-multilib                             \
    --disable-bootstrap                            \
    --disable-libgomp
make
make install

ln -sv gcc /tools/bin/cc

# 和 Glibc 一样
# 确认新工具链的基本功能（编译和链接）是否能正常运行
echo 'int main(){}' > dummy.c
$LFS_TGT-gcc dummy.c
readelf -l a.out | grep ': /tools'
# 64bit: [Requesting program interpreter: /tools/lib64/ld-linux-x86-64.so.2]
# 32bit: [Requesting program interpreter: /tools/lib/ld-linux.so.2]
rm -v dummy.c a.out
